package server;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Calendar;
import org.json.JSONObject;

import handler.ControlDataHandler;
import model.Weather;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ResourceLeakDetector;
/**
 * 处理连接请求后，数据操作
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter{
	
	static ChannelHandlerContext ctx1;
	//String[] Drict={"北风","东北偏北风","东北风","东北偏东风","东风","东南偏东风","东南风","东南偏南风","南风","西南偏南风","西南风",
		//	"西南偏西风","西风","西北偏西风","西北风","西北偏北风"};
	//该数组用做数据取平均
	//double[][]  arr = new  double [6][60];
	//各指标平均值
	//double AverCO , AverSO2 , AverNO2 , AverO3 , AverPM25 , AverPM10;
	//int i=0,j;
	//记录当前时间，做正点判断
	//int year , month , day , hour ; 
	/**
     * 网络连接时调用
     */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("客户端："+ctx.channel().remoteAddress()+" 连接到服务器:"+ctx.channel().localAddress());
		ctx.writeAndFlush(Unpooled.copiedBuffer("Welcome to connect the Server:",CharsetUtil.UTF_8));
		ctx1 = ctx;
		super.channelActive(ctx);
	}
	/**
     * 网路连接失活时调用
     */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("客户端："+ctx.channel().remoteAddress()+"与服务器断开连接");
		super.channelInactive(ctx);
	}
	/**
     * 读取数据时调用
     * 实现Json数据解析和数据库操作
     */
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
				ByteBuf buf = (ByteBuf) msg;		// 将msg转成ByteBuf对象
				String body = null;
/*				String currentTime =  new SimpleDateFormat(  //当前时间信息
						"yyyy-MM-dd HH:mm:ss").format(new Date());

				Calendar c = Calendar.getInstance();
				year = c.get(Calendar.YEAR);
				month = c.get(Calendar.MONTH)+1;
				day = c.get(Calendar.DATE);
				hour = c.get(Calendar.HOUR_OF_DAY);
				String currentTime = year+"-"+month+"-"+day+" "+hour+":00:00";
*/
				try{
					int len = buf.readableBytes();  //获取缓冲区可读字节数
					body = buf.readBytes(len).toString(Charset.forName("UTF-8"));
					System.out.println(body);
					ControlDataHandler handle = new ControlDataHandler();
					handle.Datahandle(body);
					/*
					if(body.charAt(0)!='{'){
						ctx.writeAndFlush(Unpooled.copiedBuffer("Type error",CharsetUtil.UTF_8));
					}
					else{
						JSONObject json = new JSONObject(body);
						if(i<60) {
							arr[0][i] = json.optDouble("CO",-1);
							arr[1][i] = json.optDouble("SO2",-1);
							arr[2][i] = json.optDouble("NO2",-1);
							arr[3][i] = json.optDouble("O3",-1);
							arr[4][i] = json.optDouble("PM25",-1);
							arr[5][i] = json.optDouble("PM10",-1);
						}
						else {
 							i=-1;
 							AverCO=0;
 							AverSO2=0;
 							AverNO2=0;
 							AverO3=0;
 							AverPM25=0;
 							AverPM10=0;
 							Arrays.sort(arr[0]);
 							Arrays.sort(arr[1]);
 							Arrays.sort(arr[2]);
 							Arrays.sort(arr[3]);
 							Arrays.sort(arr[4]);
 							Arrays.sort(arr[5]);
 							for(j=1;j<59;j++) {
 								AverCO += arr[0][j];
 								AverSO2 += arr[1][j];
 								AverNO2 += arr[2][j];
 								AverO3 += arr[3][j];
 								AverPM25 += arr[4][j];
 								AverPM10 += arr[5][j];
 							}
 							Weather weather = new Weather();
							
 							weather.put("CO",AverCO/58000);
 							weather.put("SO2",AverSO2/58);
 							weather.put("NO2",AverNO2/58);
 							weather.put("O3",AverO3/58);
 							weather.put("PM25",AverPM25/58);
 							weather.put("PM10",AverPM10/58);
 							weather.put("SiteID",json.optInt("SiteID", 1));
 							weather.put("Temper",json.optDouble("Temper",-1));				
 							weather.put("Hum",json.optDouble("Hum",-1));
							weather.put("Speed",json.optDouble("Speed",-1));
							weather.put("Direct",Drict[(int) ((json.optInt("Direct",0)+11.25)%360/22.5)]);
							weather.put("Press",json.optDouble("Press",-1));
							weather.put("Rainfall",json.optDouble("Rainfall",-1));
							weather.put("Time",currentTime);
						
							weather.put("CO",json.optDouble("CO",-1));
							
							weather.put("SO2",json.optDouble("SO2",-1));
							
							weather.put("NO2",json.optDouble("NO2",-1));
							
							weather.put("O3",json.optDouble("O3",-1));
							
							weather.put("PM25",json.optDouble("PM25",-1));
							
							weather.put("PM10",json.optDouble("PM10",-1));
							
							weather.put("Temper",json.optDouble("Temper",-1));
							
							weather.put("Hum",json.optDouble("Hum",-1));
							
							weather.put("Direct",Drict[(int) ((json.optInt("Direct",0)+11.25)%360/22.5)]);
							
							weather.put("Press",json.optDouble("Press",-1));
							
							weather.put("Rainfall",json.optDouble("Rainfall",-1));
							
							weather.put("Time",currentTime);
							
							if(json.getDouble("Speed")<=0.1){
								weather.put("Speed",0.0);
							}
							else{
							    weather.put("Speed",json.optDouble("Speed",-1));
							}
							
							weather.save();//数据存入数据库	
							System.out.print("********这次真的把数据写入了数据库哟*********");	
							
 						}
 						
					}
					*/
				}catch(Exception e){
					e.printStackTrace();	
				}
		//i++;
		ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
		//ReferenceCountUtil.release(buf);//释放资源，以防内存泄露 
		ctx.fireChannelRead(msg);
	}
	/**
     * 读写完成调用
     */
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
		System.out.println("读写结束!");
	}
	/**
	 * 心跳机制实现自动获取
	 */
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		ctx.writeAndFlush(Unpooled.copiedBuffer("Select all data",CharsetUtil.UTF_8));
		super.userEventTriggered(ctx, evt);
	}
    /**
     * 捕捉到异常调用
     */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println("客户端："+ctx.channel().remoteAddress()+"发生异常与服务器断开连接");
		super.exceptionCaught(ctx, cause);
	}
	/**
	 * 实现连接信息传输
	 */
	public static ChannelHandlerContext Get(){
		return ctx1;
	}

}
